<?php
/*
 * @author : Pham Huu Sam
 * @phone : 0922.926.269
 */
class Products extends CI_Controller{
    protected $_gallery_path = "";
    protected $_gallery_url = "";

    public function  __construct() {
        parent::__construct();
        $this->load->helper("url");
        $this->load->library("admin_layout"); // Sử dụng thư viện layout
        $this->admin_layout->setLayout("layout/admin"); // load file layout chính (view/layout/frontend.php)
        $this->load->Model("Msanpham");
        $this->load->library('pagination'); 
        $this->load->helper(array('form', 'url'));
        $this->load->library('form_validation');
        $this->load->Model("Mconfig");
        $this->load->Model("Mtypeproducts");
        $this->load->helper("text");  
    }

    // Controller mặc định cho trang chủ
    public function index(){
        
        $data['title'] = "Trang chủ";
        $configFrontEnd = $this->Mconfig->get_One();
        $config['base_url'] = base_url('admin/products/index/'); // xác định trang phân trang 
        $config['total_rows'] = $this->Msanpham->count_all(); // xác định tổng số record 
        $config['per_page'] = $configFrontEnd->cf_PageSize; // xác định số record ở mỗi trang
        $config['uri_segment'] = 4; // xác định segment chứa page number 
        
       
        $this->pagination->initialize($config); 
        $data['data']=$this->Msanpham->list_with_page($config['per_page'],$this->uri->segment($config['uri_segment'])); 
        
        $this->admin_layout->view("admin/products",$data);
    }

    public function addProduct() {
        $data['msg']='';
        $data['title'] = "Thêm sản phẩm";
        $data['dataTypeProducts'] = $this->Mtypeproducts->listall();

        $config = array(
            array(
                 'field'   => 'productName', 
                 'label'   => 'Tên Sản Phẩm', 
                 'rules'   => 'required'
            ),
            array(
                 'field'   => 'productPrice', 
                 'label'   => 'Giá Sản Phẩm', 
                 'rules'   => 'required|numeric'
            ),
            array(
                 'field'   => 'editor1', 
                 'label'   => 'Giá Sản Phẩm', 
                 'rules'   => 'required'
            ),
            array(
                 'field'   => 'productType', 
                 'label'   => 'Loại Sản Phẩm', 
                 'rules'   => 'required'
            ),
            array(
                 'field'   => 'productKeyWord', 
                 'label'   => 'Từ Khóa', 
                 'rules'   => 'required'
            )
        );

        $this->form_validation->set_rules($config);
        $this->form_validation->set_error_delimiters('<div class="error">', '</div>');

        if ($this->form_validation->run() == FALSE)
        {
           $this->admin_layout->view("admin/productnew",$data);
        } else {
            
            $config = array('upload_path'   => 'public/frontend/upload',
                'allowed_types' => 'gif|jpg|png',
                'max_size'      => '2000');

            
            $this->load->library("upload",$config);
            if(!$this->upload->do_upload("img")){
                $arrayErrors= array($this->upload->display_errors());
                $data['msg']  =  "<div class='error'>".$arrayErrors[0]."</div>";
                $this->admin_layout->view("admin/productnew",$data);
            }else{
                $image_data = $this->upload->data(); 

                //var_dump($image_data);
                //resize images
                $config = array("source_image" => $image_data['full_path'],
                    "new_image" => "public/frontend/sanpham",
                    "maintain_ration" => true,
                    "width" => '140',
                    "height" => "105");
                $this->load->library("image_lib",$config);
                $this->image_lib->resize();
                $slug = mb_strtolower(url_title(removesign($this->input->post('productKeyWord'))));  
                // create data
                $data = array(
                    'sanpham_Ten' => $this->input->post('productName', FALSE),
                    'sanpham_Gia' => $this->input->post('productPrice', FALSE),
                    'sanpham_HinhAnh' => $image_data['file_name'],
                    'sanpham_ChiTiet' => $this->input->post('editor1', FALSE),
                    'sanpham_Loai' => $this->input->post('productType', FALSE),
                    'sanpham_Alias' => $slug,
                    'sanpham_KeyWord' => $this->input->post('productKeyWord', FALSE)
                );
                //var_dump($data);
                $this -> Msanpham -> insertProduct($data);
                redirect('admin/products');
            }

        }

    }

    public function editProduct($idProduct) {
        $data['msg'] = '<p style="font-weight: bold">Lưu ý: Khi Sửa mà không thành công sẽ load lại dữ liệu cũ.<p>';
        $data['title'] = 'Sửa sản phẩm';
        $data['data']=$this->Msanpham->get_One($idProduct);
        $data['dataTypeProducts'] = $this->Mtypeproducts->listall();

        $config = array(
            array(
                 'field'   => 'productName', 
                 'label'   => 'Tên Sản Phẩm', 
                 'rules'   => 'required'
            ),
            array(
                 'field'   => 'productPrice', 
                 'label'   => 'Giá Sản Phẩm', 
                 'rules'   => 'required|numeric'
            ),
            array(
                 'field'   => 'editor1', 
                 'label'   => 'Giá Sản Phẩm', 
                 'rules'   => 'required'
            ),
            array(
                 'field'   => 'productType', 
                 'label'   => 'Loại Sản Phẩm', 
                 'rules'   => 'required'
            ),
            array(
                 'field'   => 'productKeyWord', 
                 'label'   => 'Từ Khóa', 
                 'rules'   => 'required'
            )
        );

        $this->form_validation->set_rules($config);
        $this->form_validation->set_error_delimiters('<div class="error">', '</div>');
        if ($this->form_validation->run() == FALSE)
        {
           $this->admin_layout->view("admin/productedit",$data);
        } else {

            if(isset($_REQUEST["save"])) {
                $config = array('upload_path'   => 'public\frontend\upload',
                    'allowed_types' => 'gif|jpg|png',
                    'max_size'      => '2000');

                
                $this->load->library("upload",$config);
                $slug = mb_strtolower(url_title(removesign($this->input->post('productKeyWord'))));
                if (empty($_FILES['img']['name'])) {
                    //echo "không file";
                    $data_edit = array(
                        'sanpham_Ten' => $this->input->post('productName', FALSE),
                        'sanpham_Gia' => $this->input->post('productPrice', FALSE),
                        'sanpham_ChiTiet' => $this->input->post('editor1', FALSE),
                        'sanpham_Loai' => $this->input->post('productType', FALSE),
                        'sanpham_Alias' => $slug,
                        'sanpham_KeyWord' => $this->input->post('productKeyWord', FALSE)
                    );
                    //var_dump($data_edit);
                    $this -> Msanpham -> updateProduct($data_edit, $idProduct);
                } else {
                    //echo "có file";
                    if(!$this->upload->do_upload("img")){
                        $arrayErrors= array($this->upload->display_errors());
                        $data['msg']  =  "<div class='error'>".$arrayErrors[0]."</div>";
                        $this->admin_layout->view("admin/productedit",$data);
                    }else{
                        $image_data = $this->upload->data();
                        //var_dump($image_data);
                        $config = array("source_image" => $image_data['full_path'],
                            "new_image" => "public/frontend/sanpham",
                            "maintain_ration" => true,
                            "width" => '140',
                            "height" => "105");
                        $this->load->library("image_lib",$config);
                        $this->image_lib->resize();

                        $data_edit = array(
                            'sanpham_Ten' => $this->input->post('productName', FALSE),
                            'sanpham_Gia' => $this->input->post('productPrice', FALSE),
                            'sanpham_HinhAnh' => $image_data['file_name'],
                            'sanpham_ChiTiet' => $this->input->post('editor1', FALSE),
                            'sanpham_Loai' => $this->input->post('productType', FALSE),
                            'sanpham_Alias' => $slug,
                            'sanpham_KeyWord' => $this->input->post('productKeyWord', FALSE)
                        );
                        //var_dump($data_edit);
                        $this -> Msanpham -> updateProduct($data_edit, $idProduct);

                    }

                }
                redirect('admin/products');
            } else {
                $this->admin_layout->view("admin/productedit",$data);
            }
        }
    }
}
?>
